package com.yundou.www.wrpc.core.net;

import com.yundou.www.wrpc.core.annotation.WRpcClient;
import com.yundou.www.wrpc.core.config.ClientConfig;

import java.util.HashMap;
import java.util.Map;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author wangweiwei
 * @since 2021/7/22
 */
public class ClientProxy {

    private static Map<String ,NettyClient> clientMap = new HashMap<>(16);


    static AtomicLong id = new AtomicLong(1);

    public static WRpcResponse request(WRpcRequest request) throws ClassNotFoundException {


        NettyClient nettyClient = clientMap.get(request.getInterfaceName());
        if (nettyClient == null) {
            try {
                nettyClient = initNettyClient(request.getInterfaceName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        request.setId(id.incrementAndGet());
        CountDownLatch downLatch = new CountDownLatch(1);


        nettyClient.doRequest(request);

        ClientBusinessHandler.doEnd(request.getId() ,downLatch);
        try {
            downLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println("222222");
        return ClientBusinessHandler.getResult(request.getId());
    }

    private static NettyClient initNettyClient(String interfaceName) {
        try {
            Class<?> aClass = Class.forName(interfaceName);
            WRpcClient wRpcClient = aClass.getAnnotation(WRpcClient.class);
            String host = wRpcClient.host();
            int port = wRpcClient.port();
            ClientConfig clientConfig = new ClientConfig();
            clientConfig.setIp(host);
            clientConfig.setPort(port);
            NettyClient nettyClient = new NettyClient(clientConfig);

            CountDownLatch countDownLatch = new CountDownLatch(1);
            CompletableFuture.runAsync(() -> {
                nettyClient.connection(countDownLatch);
            });

            try {
                countDownLatch.await();
            } catch (Exception e) {
                e.printStackTrace();
            }

//            System.out.println("111");

            clientMap.put(interfaceName , nettyClient);
            return nettyClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
